import Vuex from 'vuex'

import Vue from 'vue'

Vue.use(Vuex)

const state  = {
    count: 1
}


const getter ={
    getCount(state){
        return state.count
    }
}

// 动作，同步
const mutations={
    addOne(state,val){
        state.count = state.count + val
    },
    // 让num累减
  decrease(state,val) {
    state.count = state.count-val
  },
}
// 功能和mutations类似，但是他可以异步执行，最终调用的还是mutations中的方法
// 调用action中的方法用的是dispatch，为了和matations中的方法做区分，dispatch是异步，commit是同步
const action={
    addOneAsync({commit},val){
        setTimeout(function(){
            commit("addOne",val);
        },1000)
    },
    decreaseAsync({commit},val){
        setTimeout(function(){
            commit("decrease",val);
        },2000)
    },
    async addAndDecreaseAsync({dispatch},val){
        await dispatch('addOneAsync',val)
        await dispatch('decreaseAsync',val)
    }
}

const store = new Vuex.Store({
    state: state,
    getters: getter,
    mutations: mutations,
    actions:action
})

export default store
